package cn.enilu.flash.utils.file;

import io.minio.MinioClient;
import io.minio.errors.MinioException;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

public class FileUtils {
    /**
     * Minio服务所在地址
     */
    private final static String MINIO_ENDPOINT = "http://119.3.228.251:9000";
    /**
     * 存储桶名称
     */
    private final static String MINIO_BUCKET_NAME = "linjiashop";
    /**
     * 访问的key
     */
    private final static String MINIO_ACCESS_KEY = "sunwhite";
    /**
     * 访问的秘钥
     */
    private final static String MINIO_SECRET_KEY = "sunwhite";

    /**
     * minio 客户端
     */
    private static MinioClient minioClient;


    public static MinioClient getMinioClient() {
        try {

            if (minioClient == null) {
                minioClient = new MinioClient(MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("minio 客户端创建异常");
        }

        return minioClient;
    }

    @SneakyThrows
    public static String fileUpload(MultipartFile file) {
        String result = "";
        try {
            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = getMinioClient();

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(MINIO_BUCKET_NAME);
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MINIO_BUCKET_NAME);
            }
            String extName = ""; // 扩展名格式
            if (Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".") >= 0) {
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
            }
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + extName;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 文件存储的目录结构
            String objectName = sdf.format(new Date()) + "/" + fileName;
            // 存储文件
            minioClient.putObject(MINIO_BUCKET_NAME, objectName, file.getInputStream(), file.getContentType());
            result = MINIO_ENDPOINT + "/" + MINIO_BUCKET_NAME + "/" + objectName;
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
        return result;
    }
}
